package com.lcf.deepseek;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.lcf.deepseek.config.DeepSeekConfig;
import com.lcf.deepseek.model.DeepSeekMessage;
import com.lcf.deepseek.model.DeepSeekRequest;
import com.lcf.deepseek.model.DeepSeekResponse;
import com.lcf.framework.annotation.PermissionCheck;
import com.lcf.framework.utils.RedisCacheUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

import static com.lcf.framework.enums.PermissionEnum.DEEP_SEEK_CHAT;

/**
 * @author lcf
 */
@Tag(name = "人工智能")
@RestController
@RequestMapping("deepSeek")
public class DeepSeekController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisCacheUtils redisCacheUtils;
    @Resource
    private DeepSeekConfig deepSeekConfig;

    /**
     * deepseek连续对话
     */
    @Operation(summary = "deepseek连续对话")
    @PermissionCheck(DEEP_SEEK_CHAT)
    @PostMapping
    public String get(@RequestBody @Validated DeepSeekMessage deepSeekMessage) {
        List<DeepSeekMessage> history = redisCacheUtils.get("deepSeek");
        if (CollectionUtil.isEmpty(history)) {
            history = new ArrayList<>();
        }

        history.add(deepSeekMessage);

        // 创建 HttpHeaders 并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("content-type", "application/json");
        headers.set("Accept", "application/json");
        headers.set("Authorization", "Bearer " + deepSeekConfig.getApiKey());
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建 HttpEntity 并将请求头和请求体封装在一起
        DeepSeekRequest request = new DeepSeekRequest("deepseek-chat", history);
        HttpEntity<String> entity = new HttpEntity<>(JSONUtil.toJsonStr(request), headers);

        // 使用 RestTemplate 发送 POST 请求
        String response = restTemplate.postForObject("https://api.deepseek.com/chat/completions", entity, String.class);
        DeepSeekResponse resp = JSONUtil.toBean(response, DeepSeekResponse.class);

        DeepSeekMessage message = resp.getChoices().get(0).getMessage();

        history.add(message);
        redisCacheUtils.cache("deepSeek", history);

        return message.getContent();
    }
}
